<style scoped>
    .item-disabled {
        margin-bottom: 0;
    }
    .item-remarks /deep/ .ivu-input-wrapper,
    .item-other /deep/ .ivu-input-wrapper {
        max-width: 50%;
    }
    .item-other /deep/ .ivu-input {
        max-width: 100%;
    }
</style>
<template>
    <div class="Business">
        <Form ref="formData" :model="formData" :rules="formRules" :label-width="120">
            <Row>
                <Col span="12">
                    <FormItem label="变更主体" prop="changeSubject">
                        <RadioGroup v-model="formData.changeSubject" @on-change="changeMain">
                            <Radio v-for="(item,index) in subjectData" :key="index"
                                   :disabled="item.disabled || isFormDisabled" :label="item.value">{{item.title}}
                            </Radio>
                        </RadioGroup>
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem label="变更类型" prop="changeType">
                        <RadioGroup v-model="formData.changeType" @on-change="changeType">
                            <Radio
                                v-for="(item,index) in dataDict.CustInfoChangeTypeDict"
                                :key="index"
                                :disabled="isFormDisabled"
                                :label="item.value"
                            >{{item.title}}
                            </Radio>
                        </RadioGroup>
                    </FormItem>
                </Col>
                <Col span="24">
                    <Row type="flex" justify="center" align="middle">
                        <Col span="24">
                            <Row>
                                <Col span="12">
                                    <FormItem label="（旧）姓名" class="item-disabled">
                                        <Input clearable v-model="oldData.oldName" disabled/>
                                    </FormItem>
                                    <FormItem label="（新）姓名" prop="newName">
                                        <Input clearable v-model="formData.newName" placeholder
                                               :disabled="isFormDisabled || !(formData.changeType === 'name' || formData.changeType === 'nameAndNum')"/>
                                    </FormItem>
                                </Col>
                                <Col span="12">
                                    <FormItem label="（旧）证件类型" class="item-disabled">
                                        <!-- <Input clearable v-model="oldData.certType" disabled /> -->
                                        <Select v-model="oldData.certType" disabled>
                                            <Option :value="item.value" v-for="(item,index) in dataDict.certTypeDict"
                                                    :key="index">{{item.title}}
                                            </Option>
                                        </Select>
                                    </FormItem>
                                    <FormItem label="（新）证件类型" prop="newCertType">
                                        <!-- <Input clearable v-model="formData.newCertType" placeholder /> -->
                                        <Select v-model="formData.newCertType" :disabled="isFormDisabled || !(formData.changeType === 'nameAndNum')">
                                            <Option :value="item.value" v-for="(item,index) in dataDict.certTypeDict"
                                                    :key="index">{{item.title}}
                                            </Option>
                                        </Select>
                                    </FormItem>
                                </Col>
                                <Col span="12">
                                    <FormItem label="（旧）证件号码" class="item-disabled">
                                        <Input clearable v-model="oldData.certNo" disabled/>
                                    </FormItem>

                                    <FormItem label="（新）证件号码" prop="newCertNo">
                                        <Input clearable v-model="formData.newCertNo" placeholder
                                               :disabled="isFormDisabled || !(formData.changeType === 'nameAndNum')"/>
                                    </FormItem>
                                </Col>
                                <Col span="12">
                                    <FormItem label="（旧）有效期" class="item-disabled">
                                        <Input :value="oldData.certEndDate" disabled/>
                                        <!-- <Input clearable :value=" oldData.certEndDate" disabled /> -->
                                    </FormItem>
                                    <FormItem :required="required" label="（新）有效期" prop="newCertEndDate">
                                        <DatePicker v-model="formData.newCertEndDate" format="yyyy-MM-dd"
                                                    type="date"
                                                    :disabled="isFormDisabled || formData.isLongTerm || (formData.changeType === 'other')"></DatePicker>
                                        <Checkbox style="right: 10px" :disabled="isFormDisabled || (formData.changeType === 'other')"
                                                  @on-change="changeEndDate"
                                                  v-model="formData.isLongTerm"
                                                  type="logo-twitter" label="长期">
                                            <span>长期</span>
                                        </Checkbox>
                                    </FormItem>
                                </Col>
                                <Col span="24" v-if="formData.changeType === 'other'" class="item-other">
                                    <FormItem label="其他信息" prop="other">
                                        <Input clearable v-model="formData.other" :disabled="isFormDisabled"/>
                                    </FormItem>
                                </Col>
                            </Row>
                        </Col>
                    </Row>
                </Col>
                <Col span="24" class="item-remarks">
                    <FormItem label="简述原因" prop="remarks">
                        <Input type="textarea" clearable v-model="formData.remarks" placeholder
                               :disabled="isFormDisabled"/>
                    </FormItem>
                </Col>
                <!-- <Col span="24">
                    <FormItem label="短信验证码" prop="code">
                        <Input type="text" v-model="formData.code" />
                        <Button type="primary">发送验证码</Button>
                    </FormItem>
                </Col>-->
                <Col span="24">
                    <!-- TODO 上传身份证 -->
                    <FormItem label="上传身份证:" required>
                        <Button type="primary" @click="openUploadModal('idCard')">上传申请资料</Button>
                    </FormItem>
                </Col>
            </Row>
        </Form>
        <div class="business-change-item"></div>
        <UploadFileModal
            ref="uploadFileModal"
            :modal="isUploadFileModalOpen"
            @closeModal="closeModal"
            :param="fileParams"
            @asyncSaveFileFn="asyncSaveFileFn"
            :isPreview="isFormDisabled"
        />
    </div>
</template>
<script>
    import {findCustInfoDetial, findOldCustInfo, getOCRCustInfo} from "_p/basic/api/contract/post-loan-info-change";
    import {verifyErrorToView} from "_p/basic/assets/contract/js/utils";
    import UploadFileModal from "_p/basic/pages/contract/common/uploadFileModal/uploadFileModal";

    export default {
        components: {UploadFileModal},
        props: {
            dataDict: {
                type: Object,
                required: true
            },
            readOnly: {
                type: Boolean,
                require: true
            },
            //对象参数包含：合同号码、角色类型
            Obj: {
                type: Object,
                required: true
            },
            pageParams: {
                type: Object,
                required: true
            },
            customerInfo: {
                type: Array
            },
            // 是否是供应商
            isSP: {
                type: Boolean,
                required: true
            },
            //是否 审批完成
            isApproved: {
                type: Boolean,
                required: true
            },
            isReadOnly: {
                type: Boolean,
                default: false
            },
            isApprove: {
                type: Boolean,
                required: true
            },
        },
        computed: {
            isFormDisabled() {
                return this.isApprove || this.isApproved || this.isReadOnly
            }
        },
        data() {
            return {
                required: true,
                fileParams: {},
                isUploadFileModalOpen: false,
                uploadModal: false,
                indeterminate: false,
                checkAllType: false,
                custRole: "",
                business: "",
                showBorrower: {
                    phone: false,
                    address: false
                },
                changeTypeList: [
                    {title: '仅更新证件有效期', value: 'expirationDate'},

                    {title: '仅姓名（曾用名）', value: 'name'},

                    {title: '姓名及证件号码', value: 'nameAndNum'},

                    {title: '其他信息', value: 'other'},
                ],
                oldData: {
                    oldName:"",
                    custName: "",
                    certNo: "",
                    certType: "",
                    certStartDate: "",
                    certEndDate: "",
                    idCardDays: ""
                },
                formData: {
                    other: "",
                    reason: "",
                    changeSubject: "",
                    date: [],
                    remarks: "",
                    newName: "",
                    newCertNo: "",
                    newCertType: "",
                    changeType: "name", //默认值
                    newCertDate:[]
                },
                certDate: [],
                dateRule: {
                    newCertEndDate: [{required: true, message: "请选择有效期"}],
                },
                nameRule:{
                    newName: [{required: true, message: "请输入新姓名", trigger: "blur"}],
                },
                nameAndNumRule:{
                    newName: [{required: true, message: "请输入新姓名", trigger: "blur"}],
                    newCertType: [{required: true, message: "请选择证件类型", trigger: "change"}],
                    newCertNo: [{required: true, message: "请输入证件号码", trigger: "blur"}],
                },
                otherRule:{
                    other: [{required: true, message: "请输入其他", trigger: "blur"}],
                },
                baseRules:{
                    type: [{required: true, message: "请选择一项", trigger: "change"}],
                    changeSubject: [{required: true, message: "请选择一项", trigger: "change"}],
                    remarks: [{required: true, message: "请输入原因", trigger: "blur"}]
                },
                formRules: {
                    type: [
                        {required: true, message: "请选择一项", trigger: "change"}
                    ],
                    changeSubject: [
                        {required: true, message: "请选择一项", trigger: "change"}
                    ],
                    newName: [
                        {
                            required: true,
                            message: "请输入新姓名",
                            trigger: "blur"
                        }
                    ],
                    newCertType: [
                        {
                            required: true,
                            message: "请选择证件类型",
                            trigger: "change"
                        }
                    ],
                    newCertNo: [
                        {
                            required: true,
                            message: "请输入证件号码",
                            trigger: "blur"
                        }
                    ],
                    newCertEndDate: [
                        {
                            required: true,
                            message: "请选择有效期"
                        }
                    ],
                    other: [
                        {
                            required: true,
                            message: "请输入其他",
                            trigger: "blur"
                        }
                    ],
                    remarks: [
                        {
                            required: true,
                            message: "请输入原因",
                            trigger: "blur"
                        }
                    ]
                },
                subjectData: []
            };
        },
        watch: {
            customerInfo: function (val, oldval) {
                this.subject()
            },
            dataDict: function (val, oldval) {
                this.subject()
            },
        },
        created() {
        },
        mounted() {
            this.init();
        },
        methods: {
            init() {
                let params;
                params = typeof this.pageParams === "object" ? this.pageParams : {};
                if (!params.changeSubject) params.changeSubject = "MAIN_PERSON";
                this.changeMain(params.changeSubject);
                this.formData = Object.assign({}, this.formData, params);
                if (params.newCertEndDate === '9999-12-31') {
                    this.formData.isLongTerm = true;
                } else {
                    this.formData.isLongTerm = false;
                }
                console.log("类型默认值2", this.formData)
            },
            changeEndDate() {
                if (this.formData.isLongTerm) {
                    this.required = false;
                    this.formData.newCertEndDate = '9999-12-31';
                } else {
                    this.required = true;
                    this.formData.newCertEndDate = null;
                }

            },
            newInfo(data){
                findCustInfoDetial(data).then(res => {
                    if (res.code === "0000" && res.data) {
                        var obj = JSON.stringify(res.data);
                        let d = JSON.parse(obj);
                        console.log("请求Business数据", res.data);
                        // let date = [
                        //     res.data.newCertStartDate,
                        //     res.data.newCertEndDate
                        // ];
                        this.formData = Object.assign(
                            {},
                            this.formData,
                            res.data,
                            // { date }
                        );
                        console.log("detail",this.formData.other)
                        this.$emit('baseInfo',d)
                        if (!this.isFormDisabled) {
                            this.changeType(res.data.changeType || 'name')
                        }
                    }
                });
            },
            getBasicInfo(data) {
                if (!data) return;
                console.log("detailc参数", data)
                console.log(this.pageParams, "111111");
                console.log(this.pageParams.caseNo, "2222")
                findOldCustInfo(data).then(res => {
                    if (res.code === "0000" && res.data) {
                        console.log("请求Business old 数据", res.data);
                        if (res.data.certEndDate === "9999-12-31") {
                            this.oldData.certDate = '长期';
                        } else {
                            this.oldData.certDate = [res.data.certStartDate, res.data.certEndDate];
                        }
                        if(!this.isApproved) {
                            this.oldData = Object.assign({}, this.oldData, res.data);
                        }
                        if (this.pageParams && this.pageParams.caseNo) {
                            this.newInfo(data)
                        }else {
                            this.changeType(this.formData.changeType)
                        }
                    }
                });
            },
            changeType(type) {
                console.log(type,'changeType=====');
                const {certNo,certEndDate,certType,custName} = this.oldData;
                const {newName,newCertType,newCertNo,newCertEndDate,other,changeSubject} = this.formData;
                let formData = {
                    newName: newName || custName,
                    newCertType: newCertType || certType,
                    newCertNo: newCertNo || certNo,
                    newCertEndDate: newCertEndDate || certEndDate,
                    other: other || '',
                    changeType : type,
                    changeSubject
                };

                switch (type) {
                    case "expirationDate":
                        // formData.newName = '';
                        // formData.newCertType = '';
                        // formData.newCertNo = certNo;
                        // formData.other = '';
                        formData.newCertEndDate = this.formData.newCertEndDate || '';
                        formData.isLongTerm = false;
                        // this.formRules = Object.assign({},this.baseRules,this.dateRule);
                        break;
                    case "name":
                        formData.newName = this.formData.newName || '';
                        formData.newCertEndDate = this.formData.newCertEndDate || '';
                        formData.isLongTerm = false;
                        // formData.newCertType = '';
                        // formData.newCertNo = certNo;
                        // formData.other = '';
                        // formData.newCertEndDate = '';
                        // this.formRules = Object.assign({},this.baseRules,this.nameRule);
                        break;
                    case "nameAndNum":
                        formData.newCertEndDate = this.formData.newCertEndDate || '';
                        formData.isLongTerm = false;
                        formData.newName = this.formData.newName || '';
                        formData.newCertType = this.formData.newCertType || '';
                        formData.newCertNo = this.formData.newCertNo || '';
                        // formData.other = '';
                        // formData.newCertEndDate = '';
                        // this.formRules = Object.assign({},this.baseRules,this.nameAndNumRule);
                        break;
                    case "other":
                        // formData.newName = '';
                        // formData.newCertType = '';
                        // formData.newCertNo = certNo;
                        // formData.newCertEndDate = '';
                        // this.formRules = Object.assign({},this.baseRules);
                        break;
                }
                this.$refs.formData.resetFields()
                this.formData = Object.assign({}, this.formData, formData);
            },
            changeMain(changeSubject) {
                let contractNo = this.Obj.contractNo;
                let caseNo = this.Obj.caseNo;
                this.getBasicInfo({contractNo, changeSubject,caseNo});
            },

            /*
             * formData 数据验证 验证通过后 将数据传回父级处理  (保存/提交/审核 通用)
             * @param {String} funcName 回传给父级的方法 (注意父级需要传方法)
             * @param {Object} [data]   父级带来的数据
             */
            // formValidate(funcName, data) {
            //     if (!funcName) return;
            //
            //     this.$refs.formData.validate(valid => {
            //         if (valid) {
            //             const {changeSubject, remarks, newName, newCertNo, newCertType, changeType, newCertEndDate} = this.formData;
            //             const {custName, certNo, certType, certStartDate, certEndDate, custNo, idCardDays} = this.oldData;
            //             console.log("获取到重置的天数",this.oldData)
            //             let d = {
            //                 idCardDays,
            //                 custNo,
            //                 changeSubject,
            //                 remarks,
            //                 contractNo: this.Obj.contractNo || "",
            //                 oldName: custName || "",
            //                 newName: newName || "",
            //                 oldCertNo: certNo || "",
            //                 newCertNo: newCertNo || "",
            //                 oldCertType: certType || "",
            //                 newCertType: newCertType || "",
            //                 oldCertStartDate: certStartDate || "", // 原证件有效期起
            //                 // newCertStartDate: this.certDate[0] || "", //  新证件有效期起
            //                 oldCertEndDate: certEndDate || "", // 原证件有效期止
            //                 newCertEndDate: newCertEndDate || "", // 新证件有效期止
            //                 changeType
            //             };
            //             console.log("重置后的data",d)
            //             this.$emit(funcName, Object.assign({}, data, d));
            //         } else {
            //             this.$Message.error("必填项不能为空!");
            //             this.$emit("closeSpin");
            //             verifyErrorToView(this.$refs.formData.fields);
            //         }
            //     });
            // },

            changeCertDate(date) {
                this.certDate = date;
            },

            // 变更主体 数据
            subject() {
                if (!this.dataDict && !this.customerInfo) return;
                let dict = this.dataDict.PersonRoleTypeDict,
                    info = this.customerInfo,
                    subjectData = [];

                if (Array.isArray(dict) && dict.length > 0 && Array.isArray(info) && info.length > 0) {
                    dict.forEach((item, index) => {
                        let disabled = this.isDisabledSubject(item.value, info)
                        subjectData.push(Object.assign({}, item, {disabled}))
                    });
                    this.subjectData = subjectData;
                }
            },
            // 判断是否有 主借人共借人担保人
            isDisabledSubject(value, customerInfo) {
                let bool = true;
                if (Array.isArray(customerInfo)) {
                    for (let i = 0; i < customerInfo.length; i++) {
                        if (customerInfo[i].roleType === value) {
                            bool = false;
                            break
                        }
                    }
                }
                return bool;
            },
            // 文件上传弹窗
            uploadFile() {
                this.uploadModal = true;
            },
            messageUpload(uploadInfo) {
                console.log(uploadInfo);
                this.$Message.info("上传文件" + JSON.stringify(uploadInfo));
            },
            deleteFile(fileInfo) {
                console.log(fileInfo);
                this.$Message.info("删除文件" + JSON.stringify(fileInfo));
            },
            openUploadModal(type) {
                if(this.pageParams.caseNo || this.Obj.caseNo){
                    if (type === "idCard") {
                        console.log("canshu", this.Obj)
                            this.fileParams = {
                                belongNo: this.Obj.contractNo,
                                busiNo: this.pageParams.caseNo || 'custInfo',
                                // busiNo:this.Obj.caseNo,
                                busiType: 'custInfo',
                                busiData: {},
                                busiNodes: 'custInfo' //业务节点
                            }
                    }
                }else {
                    this.$Modal.warning({
                        title: "警告",
                        content: "请先保存业务数据！"
                    });
                    return;
                }
                this.isUploadFileModalOpen = true;
            },
            closeModal() {
                // 获取文件长度
                let l = this.$refs.uploadFileModal.getFileList()
                console.log(' 文件长度为：', l);
                this.isUploadFileModalOpen = false;
                console.log("ye面参数",this.pageParams)
                getOCRCustInfo(this.pageParams).then(res => {
                    console.log("识别的数据", res.data)
                    if (res.code === "0000") {
                        if (res.data == null) return;
                        this.formData.newName = res.data.newName;
                        this.formData.newBankAccount = res.data.newBankAccount;
                        this.formData.newCertStartDate = res.data.newCertStartDate;
                        this.formData.newCertEndDate = res.data.newCertEndDate;
                        console.log("ocr识别结果", res)
                    }
                });
            },
            /*
              * formData 数据验证 验证通过后 将数据传回父级处理  (保存/提交/审核 通用)
              * @param {String} funcName 回传给父级的方法 (注意父级需要传方法)
              * @param {Object} [data]   父级带来的数据
              */
            formValidate(funcName, data) {
                if (!funcName) return;
                this.parentFuncName = funcName;
                this.$refs.uploadFileModal.formValidate('asyncSaveFileFn', data)
            },
            asyncSaveFileFn(data) {
                console.log('ggggggggggggg, 上传成功', data);

                this.$refs.formData.validate(valid => {
                    if (valid) {
                        let d = Object.assign({}, data, this.formData, this.oldData, this.Obj);

                        this.$emit(this.parentFuncName, d)
                        // this.$emit(funcName, d);
                    } else {
                        this.$Message.error("验证不通过!");
                        this.$emit("closeSpin");
                        verifyErrorToView(this.$refs.formData.fields);
                    }
                });
            },
        }
    };
</script>
